package com.hongxun.budget.ui.activity.sg;

import android.app.DatePickerDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.dialog.ListDialog;
import com.hongxun.budget.ui.fragment.BaseFragment;
import com.hongxun.budget.ui.fragment.sg.ListInventory;
import com.hongxun.budget.ui.fragment.sg.PhotoInventory;
import com.hongxun.budget.ui.fragment.sg.PhotoScene;
import com.hongxun.budget.utils.DateUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgStrKey;
import com.hongxun.budget.utils.StringUtils;
import com.hongxun.budget.utils.XUtils;
import com.hongxun.entity.LoginInfo;
import com.hongxun.greenentity.sg.CArrivalRecordEntity;
import com.hongxun.greenentity.sg.CGoodsDetailEntity;
import com.hongxun.greenentity.sg.CScheduleReportEntity;
import com.hongxun.greenentity.sg.CStackPointEntity;
import com.hongxun.greenentity.tk.DPictureEntity;
import com.hongxun.interfaces.ResponseListener;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 新增物资到货记录
 */
public class MaterialArriveRecordAddActivity extends BaseActivity {
    @BindView(R.id.right_save)
    Button rightBtn;
    @BindView(R.id.tv1)
    TextView textView1;
    @BindView(R.id.tv2)
    TextView textView2;
    @BindView(R.id.center_title)
    TextView tvTitle;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.btn_add)
    Button btnAdd;

    BaseFragment baseFragment;
    PhotoInventory fragmentQDZP;
    PhotoScene fragmentXCZP;
    ListInventory fragmentWZQD;

    private int checkID;
    private boolean isNewAdd = false;
    private CArrivalRecordEntity entity;
    private LoginInfo loginInfo;

    @Override
    public int getLayoutId() {
        return R.layout.sg_activity_material_arrive_record_add;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        //加载本地图片时初始化
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        String uuidxm = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        tvTitle.setText(String.valueOf(SPUtils.get(context, SgStrKey.namexm, "新增物资到货记录")));
        rightBtn.setVisibility(View.VISIBLE);
        loginInfo = LoginInfo.getInfo(context);
        isNewAdd = getIntent().getBooleanExtra("isNewAdd", false);
        if (isNewAdd) {
            entity = new CArrivalRecordEntity();
            entity.setGuid(StringUtils.getUuid());
            entity.setPGuid(uuidxm);
            entity.setPName(String.valueOf(SPUtils.get(context, SgStrKey.namexm, "")));
            entity.setARTime(new Date(System.currentTimeMillis()));
            entity.setARDatastate("新增");
            entity.setARUser(loginInfo.getUserId());
            entity.setARUsername(loginInfo.getUsername());
            SPUtils.put(context, SgStrKey.uuiddh, entity.getGuid());
        } else {
            entity = SgDBUtils.getCArrivalRecord(String.valueOf(SPUtils.get(context, SgStrKey.uuiddh, "")));
            textView1.setText(entity.getSPName());
        }
        textView2.setText(DateUtils.LongToStringyyMMdd_(entity.getARTime().getTime()));
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                checkedId(checkedId);
            }
        });
        checkedId(R.id.radioButton3);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkedId2(checkID);
            }
        });
        final List<CStackPointEntity> pointEntities = SgDBUtils.getCSpListAll(uuidxm);
        textView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ListDialog<CStackPointEntity>()
                        .setTitle("选择材料堆放点")
                        .setDatas(pointEntities)
                        .setListener(new ResponseListener() {
                            @Override
                            public void response(Object... data) {
                                CStackPointEntity dfd = (CStackPointEntity) data[0];
                                textView1.setText(dfd.getSPName());
                                entity.setSPName(dfd.getSPName());
                                entity.setSPGuid(dfd.getGuid());
                            }
                        }).show(getFragmentManager(), "");
            }
        });
        //到货时间
        textView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateUtils.showDatePickerDialog(activity, R.layout.sg_dialog_datepicker, listener);
            }
        });
        //保存数据
        rightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });
    }

    private void saveData() {
        if (TextUtils.isEmpty(entity.getSPGuid())) {
            showMsg("请选择堆放地点");
            return;
        }
        Observable.just(entity).subscribeOn(Schedulers.io()).map(new Func1<CArrivalRecordEntity, Boolean>() {
            @Override
            public Boolean call(CArrivalRecordEntity entity) {
                SgDBUtils.upDataCArrivalRecordEntity(entity);
                if (fragmentWZQD != null) {
                    for (CGoodsDetailEntity detailEntity : fragmentWZQD.getDatas()) {
                        SgDBUtils.upDataCGoodsDetailEntity(0, detailEntity);
                    }
                }
                if (fragmentXCZP != null) {
                    for (DPictureEntity pictureEntity : fragmentXCZP.getDatas()) {
                        SgDBUtils.upDataDPictureEntity(pictureEntity);
                    }
                }
                if (fragmentQDZP != null) {
                    for (DPictureEntity pictureEntity : fragmentQDZP.getDatas()) {
                        SgDBUtils.upDataDPictureEntity(pictureEntity);
                    }
                }
                //新增或更新施工进度：材料到场
                String uuidxm = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
                //进度生成或更新最近记录时间
                SgDBUtils.updateCSEntity(context, uuidxm, "材料到场");
                if (!isNewAdd) return false;
                //生成材料到场记录
                CScheduleReportEntity reportEntity = new CScheduleReportEntity();
                reportEntity.setGuid(StringUtils.getUuid());
                reportEntity.setPGuid(uuidxm);
                reportEntity.setSGuid(String.valueOf(SPUtils.get(context, SgStrKey.uuidjd, "")));
                reportEntity.setSName("材料到场");
                reportEntity.setSRDatastate("新增");
                reportEntity.setSRAddtime(new Date(System.currentTimeMillis()));
                reportEntity.setSRTheme(entity.getSPName() + "到货");
                reportEntity.setSRDetails(SgDBUtils.getCGdListTj(entity.getGuid()));
                reportEntity.setSRUpdatetime(new Date(System.currentTimeMillis()));//保存一次更新一次时间
                reportEntity.setSRUser(loginInfo.getUserId());
                reportEntity.setSRUsername(loginInfo.getUsername());
                SgDBUtils.upDateCScheduleReportEntity(reportEntity);
                //进度：现场照片
                if (fragmentXCZP != null) {
                    for (DPictureEntity pictureEntity : fragmentXCZP.getDatas()) {
                        pictureEntity.setGuid(StringUtils.getUuid());
                        pictureEntity.setPPGuid(reportEntity.getGuid());
                        pictureEntity.setPLabel("进度,xc");
                        SgDBUtils.upDataDPictureEntity(pictureEntity);
                    }
                }
                //进度：资料照片
                if (fragmentQDZP != null) {
                    for (DPictureEntity pictureEntity : fragmentQDZP.getDatas()) {
                        pictureEntity.setGuid(StringUtils.getUuid());
                        pictureEntity.setPPGuid(reportEntity.getGuid());
                        pictureEntity.setPLabel("进度,zl");
                        SgDBUtils.upDataDPictureEntity(pictureEntity);
                    }
                }
                return true;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean b) {
                finish();
            }
        });

    }

    DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String month1 = "";
            String dayOfMonth1 = "";
            if (month < 10) {
                if (month == 9) {
                    month1 = "" + (month + 1);
                } else {
                    month1 = "0" + (month + 1);
                }
            } else {
                month1 = (month + 1) + "";
            }
            if (dayOfMonth < 10) {
                dayOfMonth1 = "0" + dayOfMonth;
            } else {
                dayOfMonth1 = dayOfMonth + "";
            }
            String time = year + "-" + month1 + "-" + dayOfMonth1;
            textView2.setText(time);
            entity.setARTime(new Date(DateUtils.StringTOLongyyMMdd2(time)));
        }
    };

    //切换
    private void checkedId(int checkedId) {
        checkID = checkedId;
        Bundle bundle = new Bundle();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        if (baseFragment != null) transaction.hide(baseFragment);
        switch (checkedId) {
            case R.id.radioButton1:
                btnAdd.setText("拍摄照片");
                if (fragmentQDZP == null) {
                    fragmentQDZP = new PhotoInventory();
                    bundle.putString("uuid", entity.getGuid());
                    fragmentQDZP.setArguments(bundle);
                    baseFragment = fragmentQDZP;
                    transaction.add(R.id.flayout1, fragmentQDZP, checkedId + "").commit();
                } else {
                    baseFragment = fragmentQDZP;
                    transaction.show(fragmentQDZP).commit();
                }
                break;
            case R.id.radioButton2:
                btnAdd.setText("拍摄照片");
                if (fragmentXCZP == null) {
                    fragmentXCZP = new PhotoScene();
                    bundle.putString("uuid", entity.getGuid());
                    fragmentXCZP.setArguments(bundle);
                    baseFragment = fragmentXCZP;
                    transaction.add(R.id.flayout1, fragmentXCZP, checkedId + "").commit();
                } else {
                    baseFragment = fragmentXCZP;
                    transaction.show(fragmentXCZP).commit();
                }
                break;
            case R.id.radioButton3:
                btnAdd.setText("添加物资");
                if (fragmentWZQD == null) {
                    fragmentWZQD = new ListInventory();
                    bundle.putString("uuid", entity.getGuid());
                    fragmentWZQD.setArguments(bundle);
                    baseFragment = fragmentWZQD;
                    transaction.add(R.id.flayout1, fragmentWZQD, checkedId + "").commit();
                } else {
                    baseFragment = fragmentWZQD;
                    transaction.show(fragmentWZQD).commit();
                }
                break;
        }
    }

    //底部按钮点击处理
    private void checkedId2(int checkedId) {
        switch (checkedId) {
            case R.id.radioButton1:
                XUtils.imgClick(activity);
                break;
            case R.id.radioButton2:
                XUtils.imgClick(activity);
                break;
            case R.id.radioButton3:
                fragmentWZQD.addWz();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            List<String> pathList = new ArrayList<>();
            String resour = "相册";
            if (requestCode == XUtils.CHOISE_IMG) {// 图片选择结果回调
                pathList.addAll(data.getStringArrayListExtra("result"));
            } else if (requestCode == XUtils.CAMERA_IMG) {
                resour = "相机";
                String path = data.getStringExtra("result"); // 图片地址
                pathList.add(path);
            }
            switch (checkID) {
                case R.id.radioButton1:
                    fragmentQDZP.onActivityResultBitmap(pathList, resour);
                    break;
                case R.id.radioButton2:
                    fragmentXCZP.onActivityResultBitmap(pathList, resour);
                    break;
            }
        }
    }
}
